package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.TextView;

import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAgricultural;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.ServiceInfoVO;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.viewholder.AgriculturalServiceListHolder;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.digitalchina.lxnsy.activity.old.AgriculturalServiceSearchActivity.RESULT_CODE_SERVICE_SEARCH;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：农事服务列表
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/3/23 10:32:46
 * 修改备注：
 * ================================================
 */

public class AgriculturalServiceListActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.agricultural_service_list_tv_date)
    TextView tvDateSearch;
    @Bind(R.id.agricultural_service_list_ib_search)
    ImageButton iBSearch;

    @Bind(R.id.agricultural_service_list_recycler_view)
    EasyRecyclerView recyclerView;
    @Bind(R.id.agricultural_service_list_ib_reset)
    ImageButton agriculturalServiceListIbReset;

    private RecyclerArrayAdapter adapter;

    private int page = 1;
    private int limit = 10;

    private List<ServiceInfoVO> agriculturalList = new ArrayList<>();

    private int mYear, mMonth, mDayOfMonth;//年月日
    private String searchDate;//查询时间
    private String keyWord = "";//搜索的关键字
    private final int SEARCH_REQUEST = 100;

    private String msg = "点击选择日期";
    private boolean isDate = false; // 是否使用了时间筛选

    @Override
    public void setLayout() {

        setTitle("农事服务");
        setContentLayout(R.layout.activity_agricultural_service_list);
        setRightImage(R.drawable.icon_search_withe);
    }

    @Override
    public void initMember() {
        initRecyclerView();
//        setData();
//        BusinessAgricultural.getAgriculturalList(this, searchDate, "", String.valueOf(page), String.valueOf(limit), mHandler);
//        Calendar calendar = Calendar.getInstance();
//        mYear = calendar.get(Calendar.YEAR);
//        mMonth = calendar.get(Calendar.MONTH);
//        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
//        String selectDate = mYear + "/" + (mMonth + 1) + "/" + mDayOfMonth;
//        tvDateSearch.setText(DateUtil.StringToString(selectDate, DateStyle.YYYY_MM_DD_EN));

        // 初始化时间选择的提示
        tvDateSearch.setText(msg);
        agriculturalServiceListIbReset.setVisibility(View.GONE);

    }

    private void initRecyclerView() {


        recyclerView.setLayoutManager(new LinearLayoutManager(this));

//        recyclerView.addItemDecoration(Utils.setSpaceDecoration(this, false, true, false));

        recyclerView.setAdapterWithProgress(adapter = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new AgriculturalServiceListHolder(parent);
            }
        });

        onRefresh();
    }

    @Override
    public void addListener() {
        recyclerView.setRefreshListener(this);

        adapter.setMore(R.layout.view_more, this);

        adapter.setNoMore(R.layout.view_nomore);

        adapter.setError(R.layout.view_error, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();
            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();
            }
        });

        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //点击农事服务列表查看农事服务详情
                ServiceInfoVO vo = (ServiceInfoVO) adapter.getItem(position);
//                String url = URL.SERVER + vo.getH5Url().substring(1);
                GotoUtil.gotoActivity(AgriculturalServiceListActivity.this, AgriculturalServiceDetailActivity.class, false, "toServiceDetails", vo);

            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (recyclerView == null) {
                    return;
                }
                if (recyclerView.getSwipeToRefresh().isRefreshing())
                    recyclerView.setRefreshing(false);
                switch (msg.what) {
                    case MSG.MSG_GET_AGRICULTURAL_SERVICE_LIST_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_AGRICULTURAL_SERVICE_LIST_FIELD:
                        if (adapter.getAllData().size() > 0)
                            adapter.pauseMore();
                        else
                            recyclerView.showEmpty();
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        agriculturalList = FastJsonUtil.getListBean(object.toString(), "body", "serviceInfos", ServiceInfoVO.class);
        if (page == 1) { // 刷新
            adapter.clear();
        }

        if (agriculturalList != null) {
            if (agriculturalList.size() < limit) {
                adapter.stopMore();
            }
        }

        adapter.addAll(agriculturalList);
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoActivity(this, AgriculturalServiceSearchActivity.class);
    }

    @OnClick({R.id.agricultural_service_list_tv_date, R.id.agricultural_service_list_ib_search})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.agricultural_service_list_tv_date:
                //选择日期
                showDatePicker();
                break;
            case R.id.agricultural_service_list_ib_search:
                //搜索
                gotoSearch();
                break;
        }
    }

    /**
     * 搜索页面
     */
    private void gotoSearch() {
        Intent intent = new Intent(this, AgriculturalServiceSearchActivity.class);
        startActivityForResult(intent, SEARCH_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SEARCH_REQUEST) {
            if (null != data && resultCode == RESULT_CODE_SERVICE_SEARCH) {
                //搜索返回数据
                if (null != keyWord || !"".equals(keyWord))
                    keyWord = "";
                if (null != adapter || adapter.getAllData().size() > 0) {
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                }
                keyWord = data.getStringExtra("KeyWord");

                searchData(keyWord);
            }
        }
    }

    /**
     * 根据关键字 搜索
     *
     * @param keyWord
     */
    private void searchData(String keyWord) {
        page = 1;
        searchDate = "";//按关键字搜索，时间为空
        BusinessAgricultural.getAgriculturalList(this, searchDate, "", keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
    }

    @Override
    public void onRefresh() {
        page = 1;
        BusinessAgricultural.getAgriculturalList(this, searchDate, "", keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
    }


    @Override
    public void onLoadMore() {
            page++;
            BusinessAgricultural.getAgriculturalList(this, searchDate, "", keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
    }

//    public void setData() {
//        for (int i = 0; i < 10; i++) {
//            AgriculturalServiceVO vo = new AgriculturalServiceVO();
//            vo.setTitle("苹果剪枝");
//            vo.setContent("春分剪枝要点");
//            vo.setDate("2017-03-23");
//            agriculturalList.add(vo);
//        }
//        adapter.addAll(agriculturalList);
//    }


    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        if (!isDate) {
            Calendar calendar = Calendar.getInstance();
            mYear = calendar.get(Calendar.YEAR);
            mMonth = calendar.get(Calendar.MONTH);
            mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        } else {
            String[] currentDate = StringUtil.getText(tvDateSearch).split("/");
            mYear = Integer.parseInt(currentDate[0]);
            mMonth = Integer.parseInt(currentDate[1]) - 1;
            mDayOfMonth = Integer.parseInt(currentDate[2]);
        }

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                mYear = year;
                String selectDate = year + "/" + (month + 1) + "/" + dayOfMonth;
                searchDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                tvDateSearch.setText(DateUtil.StringToString(selectDate, DateStyle.YYYY_MM_DD_EN));
                agriculturalServiceListIbReset.setVisibility(View.VISIBLE);
                page = 1;
                keyWord = "";//按时间搜索，关键字为空
                isDate = true;
                BusinessAgricultural.getAgriculturalList(AgriculturalServiceListActivity.this, searchDate, "", keyWord, String.valueOf(page), String.valueOf(limit), mHandler);
            }
        }, mYear, mMonth, mDayOfMonth);

//        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick(R.id.agricultural_service_list_ib_reset)
    public void onViewClicked() {
        tvDateSearch.setText(msg);
        agriculturalServiceListIbReset.setVisibility(View.GONE);
        isDate = false;
        searchData("");
    }
}
